package com.pai4j.ugc.service.community;

import com.pai4j.common.bean.PAIPageResponseBeanUtil;
import com.pai4j.common.enums.ContributionActionEnum;
import com.pai4j.domain.vo.response.UserBaseResponseInfoVO;
import com.pai4j.domain.vo.response.community.ContributionHistoryResponseVO;
import com.pai4j.ugc.repository.dao.ICommunityContributionHistoryDAO;
import com.pai4j.ugc.repository.entity.CommunityContributionHistoryEntity;
import com.pai4j.ugc.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 社区共建历史服务类
 *
 * @author: CYM-pai
 * @date: 2025/07/30 12:00
 **/
@Slf4j
@Service
public class CommunityContributionHistoryService {

    @Autowired
    private ICommunityContributionHistoryDAO historyDAO;
    @Autowired
    private AccountService accountService;

    /**
     * 记录操作历史
     *
     * @param contributionId 共建ID
     * @param operator       操作人
     * @param action         操作类型
     * @param oldValue       旧值
     * @param newValue       新值
     * @param description    操作描述
     */
    public void recordHistory(Long contributionId, String operator, Integer action, 
                            String oldValue, String newValue, String description) {
        CommunityContributionHistoryEntity historyEntity = new CommunityContributionHistoryEntity();
        historyEntity.setContributionId(contributionId);
        historyEntity.setOperator(operator);
        historyEntity.setAction(action);
        historyEntity.setOldValue(oldValue);
        historyEntity.setNewValue(newValue);
        historyEntity.setDescription(description);
        historyEntity.setCreateBy(operator);
        
        historyDAO.save(historyEntity);
    }

    /**
     * 根据共建ID获取历史记录列表
     *
     * @param contributionId 共建ID
     * @return 历史记录列表
     */
    public List<ContributionHistoryResponseVO> getHistoriesByContributionId(Long contributionId) {
        List<CommunityContributionHistoryEntity> historyEntities = 
                historyDAO.findByContributionIdOrderByCreateDateDesc(contributionId);
        return historyEntities.stream()
                .map(this::convertResponseVO)
                .collect(Collectors.toList());
    }

    /**
     * 分页查询历史记录列表
     *
     * @param pageNo         页码
     * @param pageSize       页大小
     * @param contributionId 共建ID（可选）
     * @param operator       操作人（可选）
     * @param action         操作类型（可选）
     * @return 分页历史记录列表
     */
    public PAIPageResponseBeanUtil<List<ContributionHistoryResponseVO>> getHistoryList(
            Integer pageNo, Integer pageSize, Long contributionId, String operator, Integer action) {
        
        // 构建分页对象，按创建时间倒序
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.by(Sort.Direction.DESC, "createDate"));
        
        Page<CommunityContributionHistoryEntity> historyEntities;
        
        // 根据条件查询
        if (contributionId != null) {
            historyEntities = historyDAO.findByContributionId(contributionId, pageable);
        } else if (operator != null) {
            historyEntities = historyDAO.findByOperator(operator, pageable);
        } else if (action != null) {
            historyEntities = historyDAO.findByAction(action, pageable);
        } else {
            historyEntities = historyDAO.findAll(pageable);
        }
        
        // 转换为VO
        List<ContributionHistoryResponseVO> histories = historyEntities.getContent().stream()
                .map(this::convertResponseVO)
                .collect(Collectors.toList());
        
        // 构建并返回分页响应工具类
        return PAIPageResponseBeanUtil.success(pageNo, pageSize, historyEntities.getTotalElements(), histories);
    }

    /**
     * 转换为响应VO
     */
    private ContributionHistoryResponseVO convertResponseVO(CommunityContributionHistoryEntity historyEntity) {
        ContributionHistoryResponseVO responseVO = new ContributionHistoryResponseVO();
        BeanUtils.copyProperties(historyEntity, responseVO);
        
        // 设置操作类型名称
        ContributionActionEnum actionEnum = getContributionActionEnum(historyEntity.getAction());
        if (actionEnum != null) {
            responseVO.setActionName(actionEnum.getActionName());
        }
        
        // 获取操作人信息
        UserBaseResponseInfoVO operatorInfo = accountService.accountInfo(historyEntity.getOperator());
        responseVO.setOperatorInfo(operatorInfo);
        
        return responseVO;
    }

    /**
     * 获取操作类型枚举
     */
    private ContributionActionEnum getContributionActionEnum(Integer action) {
        for (ContributionActionEnum actionEnum : ContributionActionEnum.values()) {
            if (actionEnum.getAction().equals(action)) {
                return actionEnum;
            }
        }
        return null;
    }
}
